<template>
  <div class="cms-upload" style="margin-top: 5px;margin-left: 10px">

    <el-upload
      class="upload-demo inline-block"
      name="uploadFile"
      :action="upLoadUrl"
      :on-change="handleChange"
      :limit="1"
      accept=".mp4"
      :data="data"
      :on-exceed="handleExceed"
      :on-success="handleAvatarSuccess"
      :on-progress="handleAvatarProgress"
      :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip"></div>
    </el-upload>
    <div style="display: inline-flex">
      <div>
        <el-button type="info" style="padding-top: 6px" @click="goPreview()">预览</el-button>
        <el-dialog :visible.sync="dialogVisible" size="small" width="550px" height="400px">
          <aliPlayer :videoId="videoId" :playAuth="playAuth" v-if="dialogVisible"></aliPlayer>
        </el-dialog>
      </div>
      <div style="padding-left: 10px;">
        <cms-attachment v-if="isShowAttachment" :field=field :attachmentFileType="attachmentFileType"
                        @getAttachmentVal="getAttachmentVal" :channelId="channelId"></cms-attachment>
      </div>
    </div>
  </div>
</template>


<script>
  import {getRand} from "@/untils/random";
  import {signParams} from "@/untils/sign";
  import api from "@/api/api";
  import axios from 'axios'

  let rand = getRand();

  export default {
    props: {
      field: {
        type: String,
        default: '',
      },
      videoId: {
        type: String,
        default: '',
      },
      //上传路径
      uploadPath: {
        type: String,
        default: ""
      },
      isShowAttachment: {
        type: Boolean,
        default: false
      },
      attachmentFileType: {
        type: String,
        default: ''
      },
      channelId: {
        type: Number,
        default: 0
      },
      action: {
        type: String,
        default: ''
      },
      upLoadWay: {
        type: Number,
        default: 0
      },
      fileRemark: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        playAuth: "",
        upLoadUrl: this.$store.state.sys.baseUrl + (this.action == "" ? this.$api.bsaeUpload : this.action),
        fileList: [],
        percentage: 0,
        status: '0',
        uploadStar: false,
        dialogVisible: false,
        data: {},
        params: {
          appId: process.env.appId,
          sessionKey: localStorage.getItem("sessionKey"),
          type: "video",
          nonceStr: rand,
          uploadPath: this.uploadPath
        },
        uploadInfo:{
          channelId: '',
          fileType: '',
          fileRemark: ''
        }
      };
    },
    methods: {
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      handleChange() {
      },
      handleAvatarSuccess(res, file) {//上传成功服务器响应
        if (res.code == "200" && res.body != '') {
          this.status = "success";
          setTimeout(() => {
            if (this.upLoadWay == 1) {
              let attachmentList = res.body;
              let attachment = attachmentList[0];
              attachment.fileRemark = this.fileRemark;
              this.uploadInfo.attachmentData = JSON.stringify(attachmentList);
              this.videoId = attachment.videoId;
              this.uploadInfo.channelId = this.channelId;
              this.uploadInfo.fileType = "video";
              this.uploadInfo.uploadWay = 2;
              this.saveAttachment();
              this.fileList = [];
              this.$emit('get', this.videoId, this.field);
              this.$emit('change', this.videoId, this.field);
            }else{
              this.fileList = [];
              this.uploadStar = false;
              this.status = "";
              this.percentage = 0;
              let videoId = res.body.uploadPath;
              this.videoId = videoId;
              this.$emit('get', videoId, this.field);
              this.$emit('change', videoId, this.field);
            }
          }, 1000);
        } else {
          this.errorMessage(res.code + ":" + res.message);
          this.status = "exception";
          setTimeout(() => {
            this.uploadStar = false;
            this.percentage = 0;
            this.status = "";
            this.videoId = "";
            this.$emit('get', this.videoId, this.field);
            this.$emit('change', this.videoId, this.field);
          }, 1000);
          this.errorMessage("上传失败:" + res.code);
        }
      },
      handleAvatarProgress(event, file, fileList) {//进度
        this.videoId = "";
        this.uploadStar = true;
        this.percentage = parseInt(event.percent.toFixed(1));
      },
      getPlayAuthInfo(videoId) {
        let url = api.getPlayAuthInfo;
        axios.post(url, {videoId: videoId}).then(res => {
          console.log(res)
          if (res.code == "200") {
            let playAuth = res.body.playAuth;
            if (this.$myUtils.isNull(playAuth)) {
              this.errorMessage("获取鉴权失败，请点击重试");
            } else {
              this.playAuth = playAuth;
              this.dialogVisible = true;
            }
          }
        });
      },
      goPreview() {
        if (this.$myUtils.isNull(this.videoId)) {
          this.errorMessage("预览失败缺少videoId");
        } else {
          this.getPlayAuthInfo(this.videoId);
        }
      },
      getAttachmentVal(result) {
        let videoId = result.fieldVal;
        this.videoId = videoId;
        this.uploadPath = result.fieldVal;
        this.$emit('get', videoId, this.field);
      },
      saveAttachment() {
        axios.post(this.$api.attachmentBatchSave, this.uploadInfo).then(res => {
          if (res.code == "200") {
            this.successMessage('上传成功');
            setTimeout(() => {
              this.uploadInfo = {}
            }, 1000);
          }
          this.loading = false;
        })
      }
    },
    created() {
      this.data = signParams(this.params, process.env.appKey);
    }
  }
</script>

<style>
  .inline-block {
    display: inline-block;
  }
</style>
